import { FolderOpenOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { useRef } from 'react';

export default function ImportBpmn(props: { onChange: (xml: string) => void }) {
  function importLocalFile() {
    const file = refFile.current?.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function (this) {
      const xmlStr: any = this.result || undefined;
      //   console.log('【正在打开本地文件】文件内容如下: ↓↓↓');
      //   console.log(xmlStr);
      props.onChange(xmlStr);

      // 清空input file的值，否则如果选择同一个文件不会触发onchange事件
      if(refFile.current) refFile.current.value = '';
    };
  }

  const refFile = useRef<HTMLInputElement | null>(null);
  return (
    <>
      <Button
        type="primary"
        size={'small'}
        icon={<FolderOpenOutlined />}
        onClick={() => {
          refFile.current?.click();
        }}
      >
        {'打开文件'}
      </Button>
      <input
        type={'file'}
        id="files"
        ref={refFile}
        accept=".xml, .bpmn"
        style={{ display: 'none' }}
        onChange={importLocalFile}
      />
    </>
  );
}
